package HibernateMapping;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Keyword {

	private int id;
	private String text;
	private String max_id;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getMax_id() {
		return max_id;
	}

	public void setMax_id(String max_id) {
		this.max_id = max_id;
	}

	public static Keyword addKeyword(String text, String max_id) {
		Transaction tms = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		Keyword temp = new Keyword();
		
		try {
			tms = session.beginTransaction();

			temp.setMax_id(max_id);
			temp.setText(text);
			session.save(temp);
			if (!tms.wasCommitted())
				tms.commit();
		} catch (RuntimeException e) {
			if (tms != null) {
				tms.rollback();
			}
			e.printStackTrace();
		} finally {
			//session.flush();
			session.close();
		}

		return temp;
	}

	public static void updateMaxID(Keyword keyword) {
		Transaction tms = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			tms = session.beginTransaction();
			session.update(keyword);
			if (!tms.wasCommitted())
				tms.commit();
		} catch (RuntimeException e) {
			if (tms != null) {
				tms.rollback();
			}
			e.printStackTrace();
		} finally {
			//session.flush();
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Keyword> getKeywords() {
		Transaction trns = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		List<Keyword> keywords = null;

		try {
			trns = session.beginTransaction();

			keywords = session.createQuery("from Keyword").list();
			
			if (!trns.wasCommitted())
				trns.commit();
		} catch (RuntimeException e) {
			if (trns != null) {
				trns.rollback();
			}
			e.printStackTrace();

		} finally {
			//session.flush();
			session.close();
		}

		return keywords;
	}
}
